/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.eit.ntc.lms.servlet.remote;

//import be.telio.mediastore.ui.upload.moeplaza.MonitoredDiskFileItemFactory;
//import be.telio.mediastore.ui.upload.moeplaza.UploadListener;
import be.telio.mediastore.ui.upload.MonitoredDiskFileItemFactory;
import be.telio.mediastore.ui.upload.UploadListener;
import com.eit.ntc.spring.utils.DateTimeUtils;
import com.eit.ntc.spring.utils.FileIOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;


/**
 *
 * @author tawatchai
 */
public class UploadRemoteServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out1 = response.getWriter();
        String status = "FAIL";
        String refId = request.getParameter("refId");
         Date d = new Date();
         String temp_path = "/content/tmp";
         String temp_filename = refId+"_"+request.getSession().getId()+"_"+DateTimeUtils.formatThaiDate(d, "yyyyMMddHHmmss");
         String temp_name = "";
         File tempDir = new File(temp_path);
         tempDir.mkdirs();
         File file = new File(tempDir,temp_filename);
         byte[] dataFile = null;
         String isUpload = null;
         String localFileValue= null;
         String dataFileName = null;
        try {
//            String isUpload = request.getParameter("isUploadFile");
//            if (isUpload!=null && isUpload.trim().equals("false")){
//                String localFile = request.getParameter("localFile");
//                File localFileData = new File(localFile);
//                if (localFileData!=null && localFileData.exists()){
//                    FileInputStream fis = new FileInputStream(localFileData);
//                    byte[] dataFile = IOUtils.toByteArray(fis);
//                     FileOutputStream fos = new FileOutputStream(file);
//                    fos.write(dataFile);
//                    fos.close();
//                    status = "SUCCESS";
//                    temp_name = localFileData.getName();
//                };
//            } else {
            //if (isUpload!=null && isUpload.trim().equals("true")){
                UploadListener listener = new UploadListener(request, 30);

                // Create a factory for disk-based file items
                FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);

                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);



                // process uploads ..
                List fileList = upload.parseRequest(request);
                Iterator iter = fileList.iterator();
                while(iter.hasNext()){
                    System.out.println("file no.....");
                    FileItem fileItem = (FileItem)iter.next();

                    if (!fileItem.isFormField()){
                        System.out.println("file:"+fileItem.getName());

                           dataFile  = fileItem.get();
                           dataFileName = fileItem.getName();
//                            if (dataFile!=null && dataFile.length>0){
//
//                                FileOutputStream fos = new FileOutputStream(file);
//                                fos.write(dataFile);
//                                fos.close();
//                                status = "SUCCESS";
                               
//
//                            };
                            //file.
                        } else {
                            System.out.println("field name:"+fileItem.getFieldName());
                            isUpload = getFieldValue("isUploadFile",fileItem,isUpload);
                            System.out.println("isUploadFile:"+isUpload);
                            localFileValue = getFieldValue("localFile", fileItem,localFileValue);
                            System.out.println("localFile:"+localFileValue);
                        };
                }
               status= doProcessFile(dataFile,file,isUpload,localFileValue);
                temp_name = doGetFileName(isUpload, localFileValue, dataFileName);
//            } ;

        }   catch (Exception e)    {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally{
            out1.print("<uploadM>");
            out1.print("<status>"+status+"</status>");
            out1.print("<file>"+file.getAbsolutePath()+"</file>");
            out1.print("</uploadM>");
            request.getSession().setAttribute("temp_filename", file.getAbsolutePath());
            request.getSession().setAttribute("temp_name", temp_name);
        }
       
    }


    public String doProcessFile(byte[] dataFile,File outputfile,String isUpload,String localFile) throws Exception{

        String status_temp = "FAIL";
        if (isUpload!=null && isUpload.trim().equals("false")){
                //String localFile = request.getParameter("localFile");
                File localFileData = new File(localFile);
                if (localFileData!=null && localFileData.exists()){
                    FileInputStream fis = new FileInputStream(localFileData);
                    dataFile = IOUtils.toByteArray(fis);
                     FileOutputStream fos = new FileOutputStream(outputfile);
                    fos.write(dataFile);
                    fos.close();
                    status_temp = "SUCCESS";
                    //temp_name = localFileData.getName();
                };
            } else {
        if (dataFile!=null && dataFile.length>0){

            FileOutputStream fos = new FileOutputStream(outputfile);
            fos.write(dataFile);
            fos.close();
            status_temp = "SUCCESS";
            //temp_name1 = FileIOUtils.getFileName(inputfile);


        };
            };
        return status_temp;
    }
    public String doGetFileName(String isUpload,String localFile,String inputfile){
        String temp1 = "";
        if (isUpload!=null && isUpload.trim().equals("false")){
            File localFileData = new File(localFile);
            temp1 = localFileData.getName();
        } else {
            temp1 = FileIOUtils.getFileName(inputfile);
        }
        return temp1;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public String getFieldValue(String fname, FileItem fileItem,String oldValue) {
        String value = oldValue;
        if (fname!=null && fileItem!=null && fileItem.getFieldName().equals(fname)){
            value = fileItem.getString();
        };
        return value;
    }

}
